package com.xyebank.ledger.service.zl.conf.jry;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;

/**
 * db配置
 * 
 * 
 * @author: rcl
 * @version: 1.0, 2018年8月30日
 */
@Configuration
// 扫描 Mapper 接口并容器管理
@MapperScan(basePackages = ZLJryDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "zljrySqlSessionFactory")
public class ZLJryDataSourceConfig {
    // 精确到 master 目录，以便跟其他数据源隔离
    static final String PACKAGE         = "com.xyebank.ledger.service.zl.dataprovider.jry";
    static final String MAPPER_LOCATION = "classpath:mapper/zl/jry/*.xml";

    @Value("${zl.jry.datasource.url}")
    private String      url;

    @Value("${zl.jry.datasource.username}")
    private String      user;

    @Value("${zl.jry.datasource.password}")
    private String      password;

    @Value("${zl.jry.datasource.driverClassName}")
    private String      driverClass;



    @Bean(name = "zljryDataSource")
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        return dataSource;
    }



    @Bean(name = "zljryTransactionManager")
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }



    @Bean(name = "zljrySqlSessionFactory")
    public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("zljryDataSource") DataSource master2DataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(master2DataSource);
        sessionFactory.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources(ZLJryDataSourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }



    @Bean(name = "zljryTransactionTemplate")
    public TransactionTemplate transactionTemplate() {
        TransactionTemplate transactionTemplate = new TransactionTemplate();
        transactionTemplate.setTransactionManager(transactionManager());
        transactionTemplate.setPropagationBehaviorName("PROPAGATION_REQUIRES_NEW");
        return transactionTemplate;
    }
}
